//
//  XML_Bloomberg_Quote.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/2/27.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//

#import "XML_Bloomberg_Quote.h"
#import "CommonFunction.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBall.h"


@implementation XML_Bloomberg_Quote
//@synthesize targetURL;
@synthesize delgeate;

- (id)init_WithURL:(NSURL*)url; {
	
    if(self=[super init])
	{
        NSLog(@"init_identify=%@",url);
        
        targetURL= url  ;
        [targetURL retain];
    }
	
	return self;
}

-(void)dealloc{
    
    NSLog(@"dealloc");     
    [targetURL release];
    
    [super dealloc];
}


- (void)main 
{ 
    
    NSLog(@"main_Start bloomberg1");
    /* 原始作法 不要刪除此段
    NSError * errorq_bloomberg = nil; 
    //NSUTF8StringEncoding  不要使用此解碼 可能有些會錯誤   
    // NSString *webpageString =   [[NSString alloc]
      //                           initWithContentsOfURL: targetURL  encoding: NSASCIIStringEncoding error//:&errorq_bloomberg]  ;
    
    
    
    
    if (errorq_bloomberg) {
        //NSASCIIStringEncoding
        NSLog(@"errorq_bloomberg=%@",errorq_bloomberg);
    }
    else {
        //NSLog(@"download=%@",webpageString);
    }
     //3.將文字資料轉成NSData資料
     // NSData *data=[NSData dataWithBytes:[webpageString UTF8String] length:[webpageString length]];    
     
     
     
    */
    
    //3.Header Field 欺騙bloomberg在User-Agent
    
   
    NSURL* url = targetURL;
    
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url]
                                    ;
   
       
    [request setValue:Bloomberg_User_Agent forHTTPHeaderField:@"User-Agent"];
    [request setValue:Bloomberg_Pragma forHTTPHeaderField:@"Pragma"]; 
    //以下可以欺騙yahoo
    //[request setValue:@"vendor=\"fff\";" forHTTPHeaderField:@"X-Client-Info"];    
    NSLog(@"main_Start bloomberg request=%@",request);    
    
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
   
    
    //4.實體要下載資料的陣列 
    bloomberg_data_quote_array=[[[NSMutableArray alloc] init] autorelease];
    
    //5.建立 data資料解析的分解器
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; //设置XML数据
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
  
   
    
    //6.委託 記得要<NSXMLParserDelegate>
    [parser setDelegate:self];
    [parser parse];
    
    //7.資料取出之後要做的事情 將bloomberg_data_array 轉成可以比較容易懂取得資料的陣列
	//NSLog(@"end Of parseXMLFile");     
    NSMutableArray *outarray=[[NSMutableArray alloc] init];
    
       
    
    //1.建構報價資料陣列
    for (NSMutableDictionary *node in bloomberg_data_quote_array) {
        NSMutableDictionary *tem_dic=[[NSMutableDictionary alloc] init];
       
        //標記：Bloomberg報價資訊流程 執行緒-取回資料後的處理
        // //1.下面資料是yahoo,bloomberg 共同有的報價資料
        NSString *code_s=@"";
        NSDate *datetime_dt=[NSDate dateWithTimeIntervalSince1970:9999];  
        NSNumber *open_num=[NSNumber numberWithDouble:0];
        NSNumber *high_num=[NSNumber numberWithDouble:0];        
        NSNumber *low_num=[NSNumber numberWithDouble:0];
        NSNumber *close_num=[NSNumber numberWithDouble:0];        
        NSNumber *updown_num=[NSNumber numberWithDouble:0]; 
        NSNumber *updown_p_num=[NSNumber numberWithDouble:0];
        NSNumber *volume_num=[NSNumber numberWithDouble:0];        
        NSNumber *PE_num=[NSNumber numberWithDouble:0]; 
        NSNumber *MarketCap_num=[NSNumber numberWithDouble:0];       
        NSNumber *low_52week_num=[NSNumber numberWithDouble:0];
        NSNumber *high_52week_num=[NSNumber numberWithDouble:0];       
              
        
        //代碼-code
        if ([node objectForKey:@"px:WBTKR"]) {
            code_s=[node objectForKey:@"px:WBTKR"];
        }
        
        //時間-datetime
        if ([node objectForKey:@"px:UTIME"]) {
            datetime_dt=[NSDate dateWithTimeIntervalSince1970:[[node objectForKey:@"px:UTIME"] doubleValue] ]; 
        }
           
        //開盤價-open
        if ([node objectForKey:@"px:PR006"]) {
            
            open_num=[NSNumber numberWithDouble:[[node objectForKey:@"px:PR006"] doubleValue]];
        }
            
        //收盤價-close
        if ([node objectForKey:@"px:PR005"]) {
           // NSLog(@"收盤價=%@",[node objectForKey:@"px:PR005"])  ;  
            close_num=[NSNumber numberWithDouble:[[node objectForKey:@"px:PR005"] doubleValue]];            
        }
        
        //最高價        
        if ([node objectForKey:@"px:PR007"]) {
            
            high_num=[NSNumber numberWithDouble:[[node objectForKey:@"px:PR007"] doubleValue]]; 
        }
                 
        //最低價        
        if ([node objectForKey:@"px:PR008"]!=nil) {
           // NSLog(@"最低價=%@",[node objectForKey:@"px:PR008"])  ;   
            low_num=[NSNumber numberWithDouble:[[node objectForKey:@"px:PR008"] doubleValue]];            
        }
                
        //漲跌
        if ([node objectForKey:@"px:PR051"]) {
           // NSLog(@"漲跌=%@",[node objectForKey:@"px:PR051"])  ;  
             updown_num=[NSNumber numberWithDouble:[[node objectForKey:@"px:PR051"] doubleValue]];              
        }
         
        //漲跌幅
        if ([node objectForKey:@"px:PR052"]) {
           // NSLog(@"漲跌幅=%@",[node objectForKey:@"px:PR052"])  ;  
              updown_p_num=[NSNumber numberWithDouble:[[node objectForKey:@"px:PR052"] doubleValue]];             
            
        }
         
        //成交量        
        if ([node objectForKey:@"px:PR013"]!=nil) {
              volume_num=[NSNumber numberWithDouble:[[node objectForKey:@"px:PR013"] doubleValue]];          
        }
           
               
        //PE        
        if ([node objectForKey:@"px:RR900"]!=nil) {
            PE_num=[NSNumber numberWithDouble: [[node objectForKey:@"px:RR900"] doubleValue]];          
        }
                 
        //MarketCap        
        if ([node objectForKey:@"px:RR902"]!=nil) {
            MarketCap_num= [NSNumber numberWithDouble: [[node objectForKey:@"px:RR902"] doubleValue]];   
            
            
            
        }
        
        
        //high 52 week        
        if ([node objectForKey:@"px:HS001"]!=nil) {
            high_52week_num=[NSNumber numberWithDouble: [[node objectForKey:@"px:HS001"]doubleValue]];           
        }
                   
        //low 52 week        
        if ([node objectForKey:@"px:HS002"]!=nil) {
            low_52week_num=[NSNumber numberWithDouble: [[node objectForKey:@"px:HS002"]doubleValue]];            
        }
       
        //標記：報價-資料是透過網路上取出報價資料來載入_all 4.bloomberg 資料輸入        
        [tem_dic setObject:code_s forKey:DB_object_sqlite_basic_code];
        [tem_dic setObject:datetime_dt forKey:DB_object_quote_all_datetime];         
        [tem_dic setObject:open_num forKey:DB_object_quote_all_open];
        [tem_dic setObject:close_num forKey:DB_object_quote_all_close];
        [tem_dic setObject:high_num forKey:DB_object_quote_all_high];
        [tem_dic setObject:low_num forKey:DB_object_quote_all_low];
        [tem_dic setObject:updown_num forKey:DB_object_quote_all_updown];
        [tem_dic setObject:updown_p_num forKey:DB_object_quote_all_updown_p];
        [tem_dic setObject:volume_num forKey:DB_object_quote_all_vol];
        [tem_dic setObject:PE_num forKey:DB_object_quote_all_PE];
        [tem_dic setObject:MarketCap_num forKey:DB_object_quote_all_MarketCap];         
        [tem_dic setObject:high_52week_num forKey:DB_object_quote_all_high_52week];   
        [tem_dic setObject:low_52week_num forKey:DB_object_quote_all_low_52week];
        [tem_dic setObject:[NSNumber numberWithDouble: 999 ] forKey:DB_object_quote_all_sample1];        
        
        
        //2.bloomberg獨有
        //標記：報價-資料是透過網路上取出報價資料來載入_bloomberg 4.bloomberg 資料輸入 輸入真的值  666        
        {
            //簡介        
            NSString *introduce=@"";        
            NSNumber *return_52week_num=[NSNumber numberWithDouble:0];
            
            if ([node objectForKey:@"px:DS318"]!=nil) {
                introduce=[node objectForKey:@"px:DS318"];          
            }
            
            //return 52 week        
            if ([node objectForKey:@"px:RT012"]!=nil) {
                return_52week_num=[NSNumber numberWithDouble: [[node objectForKey:@"px:RT012"]doubleValue]];   
                
            }
            
            [tem_dic setObject:introduce forKey:DB_object_quote_Bloomberg_introduce];         
            [tem_dic setObject:return_52week_num forKey:DB_object_quote_Bloomberg_return_52week];        
            [tem_dic setObject:[NSNumber numberWithDouble:666 ] forKey:DB_object_quote_Bloomberg_sample1];             
            
        }
        
                 
        
        //3.下面資料是YAHOO 獨有
        //標記：報價-資料是透過網路上取出報價資料來載入_yahoo 4.bloomberg 資料輸入 輸入假的值 111       
        {
            
            NSString *currency_s=@"";
            NSString *exchange_s=@"";
            
            NSNumber *dividend_rate_num=[NSNumber numberWithDouble: 0 ]; 
            NSNumber *dividend_yield_num=[NSNumber numberWithDouble:0 ];       
            NSNumber *eps_curr_year_num=[NSNumber numberWithDouble: 0];
            NSNumber *realtime_change_num=[NSNumber numberWithDouble: 0 ]; 
            NSNumber *realtime_chg_percent_num=[NSNumber numberWithDouble: 0];       
            NSNumber *realtime_price_num=[NSNumber numberWithDouble: 0];
            NSDate   *realtime_ts=[NSDate dateWithTimeIntervalSince1970:0 ]; 
            
            NSNumber *after_mkt_change_num=[NSNumber numberWithDouble: 0 ]; 
            NSNumber *after_mkt_chg_percent_num=[NSNumber numberWithDouble:0 ];       
            NSNumber *after_mkt_price_num=[NSNumber numberWithDouble:0 ];
            
            
            [tem_dic setObject:after_mkt_change_num forKey:DB_object_quote_Yahoo_after_mkt_change];   
            [tem_dic setObject:after_mkt_chg_percent_num forKey:DB_object_quote_Yahoo_after_mkt_chg_percent];
            [tem_dic setObject:after_mkt_price_num forKey:DB_object_quote_Yahoo_after_mkt_price];             
            [tem_dic setObject:currency_s forKey:DB_object_quote_Yahoo_currency];   
            [tem_dic setObject:exchange_s forKey:DB_object_quote_Yahoo_exchange];
            [tem_dic setObject:dividend_rate_num forKey:DB_object_quote_Yahoo_dividend_rate];               
            [tem_dic setObject:dividend_yield_num forKey:DB_object_quote_Yahoo_dividend_yield];         
            [tem_dic setObject:eps_curr_year_num forKey:DB_object_quote_Yahoo_eps_curr_year]; 
            [tem_dic setObject:realtime_change_num forKey:DB_object_quote_Yahoo_realtime_change];   
            [tem_dic setObject:realtime_chg_percent_num forKey:DB_object_quote_Yahoo_realtime_chg_percent];
            [tem_dic setObject:realtime_price_num forKey:DB_object_quote_Yahoo_realtime_price];               
            [tem_dic setObject:realtime_ts forKey:DB_object_quote_Yahoo_realtime_ts];                
            [tem_dic setObject:[NSNumber numberWithDouble:111 ] forKey:DB_object_quote_Yahoo_sample1];         
        }
                
        
        //4.Google特有的資料
        //標記：報價-資料是透過網路上取出報價資料來載入_google 4.bloomberg 資料輸入 輸入假的值111        
        {
            NSDate *Google_after_mkt_time =[NSDate dateWithTimeIntervalSince1970:9999];       
            NSNumber *Google_after_mkt_price_num=[NSNumber numberWithDouble: 0 ];         
            NSNumber *Google_after_mkt_change_num=[NSNumber numberWithDouble: 0 ]; 
            NSNumber *Google_after_mkt_chg_percent_num=[NSNumber numberWithDouble: 0 ];         
            NSNumber *Google_shares_num=[NSNumber numberWithDouble: 0 ];         
            NSNumber *Google_beta_num=[NSNumber numberWithDouble: 0 ]; 
            NSNumber *Google_institution_own_num=[NSNumber numberWithDouble: 0 ];           
            NSNumber *Google_delay_num=[NSNumber numberWithDouble: 0 ];         
            NSNumber *Google_30average_vol_num=[NSNumber numberWithDouble: 0 ]; 
            NSNumber *Google_timezone=[NSNumber numberWithDouble: 0 ];         
            
            [tem_dic setObject:Google_after_mkt_time forKey:DB_object_quote_Google_after_mkt_time];         
            [tem_dic setObject:Google_after_mkt_price_num forKey:DB_object_quote_Google_after_mkt_price];  
            [tem_dic setObject:Google_after_mkt_change_num forKey:DB_object_quote_Google_after_mkt_change];         
            [tem_dic setObject:Google_after_mkt_chg_percent_num forKey:DB_object_quote_Google_after_mkt_chg_percent];  
            [tem_dic setObject:Google_shares_num forKey:DB_object_quote_Google_shares];         
            [tem_dic setObject:Google_beta_num forKey:DB_object_quote_Google_beta];  
            [tem_dic setObject:Google_institution_own_num forKey:DB_object_quote_Google_institution_own];         
            [tem_dic setObject:Google_delay_num forKey:DB_object_quote_Google_delay];  
            [tem_dic setObject:Google_30average_vol_num forKey:DB_object_quote_Google_30average_vol];      
            [tem_dic setObject:Google_timezone forKey:DB_object_quote_Google_timezone];
            [tem_dic setObject:[NSNumber numberWithInt:111] forKey:DB_object_quote_Google_sample1];        
            
        }
               
        [outarray addObject:tem_dic];        
        [tem_dic release];
    }
    
    //2.將報價資料陣列更新到物件上
    [CommonFunction after_quotefinished_outarray:outarray delgeate:delgeate];  
    
     //標記：Bloomberg報價資訊流程 執行緒-資料處理結束產生Dictionaey 回報給上一層
    [(Data_Model *)delgeate performSelectorOnMainThread:@selector(Quote_Finished:) withObject:outarray waitUntilDone:YES];    
    
    
    
    [parser release];
    
    [request release];
    
    
    
     [outarray release]; 
    // [webpageString release];    
    
      //NSLog(@"main_End");    
}


#pragma mark -
#pragma mark 解析xml

/* 如何解析xml資料說明
 
 1.以下是從網路上下載的xml 文件
 http://m.bloomberg.com/iphone/apps/wds/SymbolSearch.asp?Query=2330&From=1&Count=20&bbipver=1.0.9,17243a4e72c7eadd0e9823cd887f97212efa43fa,iPad,iPhone%20OS,5.0.1,zh_TW,zh-Hant
 2012-02-26 18:19:16.817 CodeSign_MacStockApp[10560:ad03] bloomberg=<?xml version="1.0" encoding="ISO-8859-1" ?>
 <px:MarketData xmlns:px="http://www.bloomberg.com/bloomberg-web-pricing" systime="1330251555989" >
 <px:SymbolSearch AllTotalMembers="294179" Count="4" From="1" Query="2330" TotalMembers="4">
 <px:Security>
 <px:WBTKR>2330:TT</px:WBTKR>
 <px:DS520>Taiwan Semiconductor Manufacturing Co Ltd</px:DS520>
 <px:DS290>Taiwan</px:DS290>
 <px:DS213>Common Stock</px:DS213>
 <px:DS202>Semicon Compo-Intg Circu</px:DS202>
 </px:Security>
 <px:Security>
 <px:WBTKR>2330:HK</px:WBTKR>
 <px:DS520>China Uptown Group Co Ltd</px:DS520>
 <px:DS290>Hong Kong</px:DS290>
 <px:DS213>Common Stock</px:DS213>
 <px:DS202>Computers-Integrated Sys</px:DS202>
 </px:Security>
 <px:Security>
 <px:WBTKR>2330:JP</px:WBTKR>
 <px:DS520>SmartEbook.com Co Ltd</px:DS520>
 <px:DS290>Japan</px:DS290>
 <px:DS213>Common Stock</px:DS213>
 <px:DS202>Internet Content-Entmnt</px:DS202>
 </px:Security>
 <px:Security>
 <px:WBTKR>FTDOLX:US</px:WBTKR>
 <px:DS520>First Trust 2330 - Weak Dollar Plus Portfolio - Series 2</px:DS520>
 <px:DS290>USA</px:DS290>
 <px:DS213>UIT</px:DS213>
 <px:DS202></px:DS202>
 </px:Security>
 </px:SymbolSearch>
 
 原始文字資料解釋：
 請注意上面的分類中 通用格式如下：<標記>內容資料</標記> 
 也就是這樣看：先看哪個標記開始，再取出內容資料，最後找到標記結束
 
 2.xml分解所需要的原始文字資料
 
 
 
 3.建立委託
 
 4.委託方法
 
 */


//以下三個method為我們最常使用的NSXMLParserDelegate method


//1. 於遇到XML tag開頭時被呼叫，可取得tag的名稱以及tag裡的attribute

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
	//NSLog(@"Did start element");
	
    if ( [elementName isEqualToString:@"px:Security"]) {
         
        //節點開始
        bloomberg_node=[[NSMutableDictionary alloc] init];
        node_name=@"";
        return;
    }
    
    if ( [elementName isEqualToString:@"px:WBTKR"] ) {
		 
        node_name=@"px:WBTKR";
        return;
    }
    if ( [elementName isEqualToString:@"px:PR005"] ) {
		 
        node_name=@"px:PR005";
        return;
    }    
    if ( [elementName isEqualToString:@"px:PR006"] ) {
		 
        node_name=@"px:PR006";
        return;
    }
    if ( [elementName isEqualToString:@"px:PR007"] ) {
		 
        node_name=@"px:PR007";
        return;
    }  
    if ( [elementName isEqualToString:@"px:PR008"] ) {
		 
        node_name=@"px:PR008";
        return;
    }    
    if ( [elementName isEqualToString:@"px:UTIME"] ) {
		 
        node_name=@"px:UTIME";
        return;
    }  
    if ( [elementName isEqualToString:@"px:PR051"] ) {
		 
        node_name=@"px:PR051";
        return;
    }  
    if ( [elementName isEqualToString:@"px:PR052"] ) {
		 
        node_name=@"px:PR052";
        return;
    }
    if ( [elementName isEqualToString:@"px:PR013"] ) {
		 
        node_name=@"px:PR013";
        return;
    }  
    if ( [elementName isEqualToString:@"px:DS318"] ) {
        
        node_name=@"px:DS318";
        return;
    }  
    if ( [elementName isEqualToString:@"px:RR900"] ) {
        
        node_name=@"px:RR900";
        return;
    }  
    if ( [elementName isEqualToString:@"px:RR902"] ) {
        
        node_name=@"px:RR902";
        return;
    }      
    //==
    if ( [elementName isEqualToString:@"px:HS001"] ) {
        
        node_name=@"px:HS001";
        return;
    }  
    if ( [elementName isEqualToString:@"px:HS002"] ) {
        
        node_name=@"px:HS002";
        return;
    }  
    if ( [elementName isEqualToString:@"px:RT012"] ) {
        
        node_name=@"px:RT012";
        return;
    }      
    
    
}

//2. 找到XML tag所包含的內容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //NSLog(@"foundCharacters %@", string);
    if ([string retainCount]>0) {
        node_value=[string retain];
    }
    else {
        node_value=@"";
    }
    
}


//3. 於遇到XML tag結尾時被呼叫

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    //NSLog(@"didEndElement");
    if ( [elementName isEqualToString:@"px:Security"]) {
         
        //節點結束
        [bloomberg_data_quote_array addObject:bloomberg_node];
        [bloomberg_node release];
        return;
    }
    if ( [elementName isEqualToString:@"px:WBTKR"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    if ( [elementName isEqualToString:@"px:PR005"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    
    
    if ( [elementName isEqualToString:@"px:PR006"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }

    if ( [elementName isEqualToString:@"px:PR007"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    if ( [elementName isEqualToString:@"px:PR008"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    if ( [elementName isEqualToString:@"px:UTIME"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    
    if ( [elementName isEqualToString:@"px:PR051"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    
    if ( [elementName isEqualToString:@"px:PR052"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    if ( [elementName isEqualToString:@"px:PR013"] ) {
		 
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    if ( [elementName isEqualToString:@"px:DS318"] ) {
        
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    
    if ( [elementName isEqualToString:@"px:RR900"] ) {
        
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }    
    if ( [elementName isEqualToString:@"px:RR902"] ) {
        
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }    
    //===
    if ( [elementName isEqualToString:@"px:HS001"] ) {
        
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
    
    if ( [elementName isEqualToString:@"px:HS002"] ) {
        
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }    
    if ( [elementName isEqualToString:@"px:RT012"] ) {
        
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }        
    
    
    
}
 

@end
